package com.esdk.sql;

import com.esdk.sql.orm.IRow;
import com.esdk.sql.orm.ParentRow;
import com.esdk.sql.orm.RowUtils;
import com.esdk.utils.EasyStr;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SqlServerDialect extends SqlDialect{

	public SqlServerDialect(){
		super(ConnMetaData.DatabaseProductName_MsSQL,null,null);
	}
	
	public SqlServerDialect(Connection conn){
		super(conn);
	}
	
	public SqlServerDialect(String databaseProductName){
		super(databaseProductName);
	}

  @Override public StringBuilder getSQL(Columns columns,Froms froms,Wheres wheres,String distinct,int offset
			,int limit,OrderBys orderbys,GroupBys groupbys){
  	if(limit>0){
    	StringBuilder stmtSql=join("SELECT",distinct,columns.assemble(),froms.assemble(),wheres.assemble()
    			,groupbys.assemble(),orderbys.assemble(),offset>=0?"OFFSET ".concat(offset+"").concat(" ROWS"):""
    			,limit>0?"FETCH NEXT ".concat(limit+"").concat(" ROWS ONLY"):"");
			return stmtSql;
		}else
			return super.getSQL(columns,froms,wheres,distinct,offset,limit,orderbys,groupbys);
	}

	@Override
	public StringBuilder parse(Columns columns,Froms froms,Wheres wheres,String distinct,int offset,int limit,
			OrderBys orderbys,GroupBys groupbys){
		if(limit>0){
			StringBuilder pstmtSql=join("SELECT",distinct,columns.assemble(),froms.assemble(),wheres.getPstmtSql()
					,groupbys.assemble(),orderbys.assemble(),offset>=0?"OFFSET ".concat(offset+"").concat(" ROWS"):""
	    			,limit>0?"FETCH NEXT ".concat(limit+"").concat(" ROWS ONLY"):"");
			return pstmtSql;
		}else
			return super.parse(columns,froms,wheres,distinct,offset,limit,orderbys,groupbys);
	}
	
	/**TODO 待用到mssql2012时才实现*/
	@Override
	public StringBuilder parseBatchReplace(String tableName,List<IRow> prs,boolean ignoreRowChanged){
		String[] fields=prs.get(0).getColumns();
		ArrayList<Object[]> values=new ArrayList(prs.size());
		for(IRow row:prs) {
			if(ignoreRowChanged || row.isChanged()) {
				if(row instanceof ParentRow){
					if(((ParentRow)row).getPKID()==null)
						((ParentRow)row).setPKID(RowUtils.genNextPrimaryId());
					((ParentRow)row).fillCommonFields();
				}
			}
			List result=row.toList();
			values.add(result.toArray());
		}
		StringBuilder sb=new StringBuilder().append("Replace Into ").append(tableName).append(" (").append(EasyStr.arrToStr(fields)).append(")").append(" values ");
    for(Iterator<Object[]> iter=values.iterator();iter.hasNext();){
    	Object[] array=iter.next();
    	sb.append("(");
    	for(int i=0,n=array.length;i<n;i++){
    		sb.append(SQLAssistant.getStmtSqlValue(array[i]));
    		if(i<n-1)
    			sb.append(",");
    	}
    	sb.append(")");
    	if(iter.hasNext())
    		sb.append(",");
    }
    return sb;
	}
}
